package app.framework.security.captcha;

import app.framework.constant.FrameworkCacheConstants;
import jasmine.framework.cache.CacheUtil;
import jasmine.framework.common.util.CheckUtil;
import jasmine.framework.common.util.StringUtil;

import java.util.UUID;

/**
 * @author mh.z
 */
public class CaptchaCacheUtil {

    /**
     * 保存验证码
     *
     * @param captchaCode
     * @return
     */
    public static String save(String captchaCode) {
        CheckUtil.notNull(captchaCode, "captchaCode null");

        String captchaKey = UUID.randomUUID().toString();
        CacheUtil.set(FrameworkCacheConstants.CACHE_CATEGORY_CAPTCHA,
                captchaKey, captchaCode, FrameworkCacheConstants.CACHE_TIMEOUT_CAPTCHA);

        return captchaKey;
    }

    /**
     * 清除验证码
     *
     * @param captchaKey
     */
    public static void remove(String captchaKey) {
        if (StringUtil.isNotEmpty(captchaKey)) {
            String cacheKey = captchaKey;

            CacheUtil.remove(FrameworkCacheConstants.CACHE_CATEGORY_CAPTCHA, cacheKey);
        }
    }

    /**
     * 检查验证码
     *
     * @param captchaKey
     * @param captchaCode
     * @return
     */
    public static boolean check(String captchaKey, String captchaCode) {
        if (captchaKey == null || captchaCode == null) {
            return false;
        }

        String cachedValue = CacheUtil.get(FrameworkCacheConstants.CACHE_CATEGORY_CAPTCHA,
                captchaKey, String.class);

        return StringUtil.equalsIgnoreCase(cachedValue, captchaCode);
    }

}
